<?php

declare(strict_types=1);

namespace think\auth\service;

use think\App;
use think\auth\model\RoleModel;
use think\auth\model\UserModel;
use think\Collection;
use think\db\exception\DbException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;

class Role
{
    public function __construct(App $app)
    {
        $this->app = $app;
    }

    /**
     * 取出所有角色
     * @return Collection|array
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function List(): Collection|array
    {
        return RoleModel::select();
    }

    /**
     * 创建一个角色
     * @param string $roleName
     * @return RoleModel
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function Create(string $roleName): RoleModel
    {
        $role = RoleModel::FindByName($roleName);
        if(!empty($role) && !$role->isEmpty()) return $role;
        return RoleModel::create(['name'=>$roleName]);
    }

    /**
     * 获取角色
     * @param int|string $roleId
     * @return RoleModel|null
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function Fetch(int|string $roleId): RoleModel|null
    {
        return RoleModel::FindById($roleId);
    }

    /**
     * 删除角色
     * @param RoleModel $role
     * @return bool|int
     */
    public function Delete(RoleModel $role): bool|int
    {
        UserModel::where('role', $role->id)->save(['role'=>0]);
        return RoleModel::where(['id'=>$role->id])->delete();
    }
}
